package com.xxgc.wujiaoredis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.xxgc.wujiaoredis.entity.GoodsEntity;
import com.xxgc.wujiaoredis.entity.GoodsEntityMapper;
import com.xxgc.wujiaoredis.service.IGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class GoodsServiceImpl implements IGoodsService {

    @Autowired
    private GoodsEntityMapper goodsEntityMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public List<GoodsEntity> selectGoodsByMerchantId(String merchantId) {
        //组合成了一个key
        String key = "merchantId:"+merchantId;
        //如果缓存里面有key 有数据
        if(redisTemplate.hasKey(key)){
            log.info("----------从缓存中获取----------");
            List<GoodsEntity> goodsEntities = (List<GoodsEntity>) redisTemplate.opsForValue().get(key);
            return goodsEntities;
        }else{
            log.info("从数据库获取的");
            //条件构造器
            QueryWrapper<GoodsEntity> qw = new QueryWrapper<>();
            qw.eq("merchant_id",merchantId);
            List<GoodsEntity> goodsEntities = goodsEntityMapper.selectList(qw);
            //给缓存一份
            redisTemplate.opsForValue().set(
                    key,
                    goodsEntities,
                    30,
                    TimeUnit.SECONDS
            );
            return goodsEntities;
        }
    }
}
